import { useDeferredValue, useState, memo } from 'react'

function ListItem({ children }) {
	let now = performance.now()
	// 考点1：useDeferred 需要搭配 memo 包裹组件，且组件渲染之前存在大量数据操作或者密集任务操作的情况下才有效果。
	// 可中断，降低渲染优先级。
	while (performance.now() - now < 3) {}
	return <div className="ListItem">{children}</div>
}

const MySlowList = memo(function ({ text }) {
	let items = []
	for (let i = 0; i < 80; i++) {
		items.push(
			<ListItem key={i}>
				Result #{i} for "{text}"
			</ListItem>,
		)
	}
	return (
		<div className="border">
			<p>
				<b>Results for "{text}":</b>
			</p>
			<ul className="List">{items}</ul>
		</div>
	)
})

export default function UseDeferredValue(props) {
	const [text, setText] = useState('hello')
	const deferredText = useDeferredValue(text)

	const handleChange = (e) => {
		setText(e.target.value)
	}

	return (
		<div>
			<h3>UseDeferredValue</h3>
			<input value={text} onChange={handleChange} />
			<p>{deferredText}</p>
			<MySlowList text={deferredText}></MySlowList>
		</div>
	)
}
